package com.lujianfei.powerinput.ui.noteList.presenter;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;

import com.lujianfei.powerinput.database.NoteItemFieldModel;
import com.lujianfei.powerinput.database.NoteItemModel;
import com.lujianfei.powerinput.database.TemplateModel;
import com.lujianfei.powerinput.ui.noteList.NoteListAddActivity;
import com.lujianfei.powerinput.ui.noteList.NoteListEditActivity;
import com.lujianfei.powerinput.ui.noteList.NoteListViewActivity;
import com.lujianfei.powerinput.ui.noteList.base.NoteListContract;
import com.lujianfei.powerinput.ui.setting.SettingActivity;
import com.lujianfei.powerinput.ui.template.TemplateActivity;
import com.lujianfei.powerinput.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AlertDialog;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.BiConsumer;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class NoteListPresenter implements NoteListContract.Presenter {
    private final static String TAG = "NoteListPresenter";
    private static final int REQUEST_TEMPLATE = 100;
    private final NoteListContract.View view;
    private List<NoteItemModel> noteItemModels;
    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();
    public NoteListPresenter(NoteListContract.View view) {
        this.view = view;
    }

    @Override
    public void onTitleLeftImageClick() {
        view.currentActivity().startActivity(new Intent(view.currentActivity(),SettingActivity.class));
    }

    @Override
    public void initData() {
        Observable<List<String>> observable = Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(ObservableEmitter<List<String>> emitter) throws Exception {
                Log.i(TAG,"subscribe on "+Thread.currentThread());
                List<String> data = getData();
                emitter.onNext(data);
            }
        });

        DisposableObserver<List<String>> disposableObserver = new DisposableObserver<List<String>>() {
            @Override
            public void onNext(List<String> data) {
                Log.i(TAG,"onNext on "+Thread.currentThread());
                view.updateList(data);
                if (null == data || data.isEmpty()){
                    view.showEmptyView();
                }else{
                    view.hideEmptyView();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(disposableObserver);
        mCompositeDisposable.add(disposableObserver);
    }

    @Override
    public void onTitleRightImageClick() {
        Intent intent = new Intent(view.currentActivity(), TemplateActivity.class);
        intent.putExtra(TemplateActivity.OPER_TYPE,TemplateActivity.TYPE_SELECT);
        view.currentActivity().startActivityForResult(intent,REQUEST_TEMPLATE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode!=Activity.RESULT_OK){
            return;
        }
        switch (requestCode){
            case REQUEST_TEMPLATE:{
                TemplateModel templateModel = data.getParcelableExtra("data");
                Intent intent = new Intent(view.currentActivity(),NoteListAddActivity.class);
                intent.putExtra("templateData",templateModel);
                view.currentActivity().startActivity(intent);
            }
            break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view2, int i, long l) {
        NoteItemModel noteItemModel = noteItemModels.get(i);
        Intent intent = new Intent(view.currentActivity(),NoteListViewActivity.class);
        intent.putExtra("data",noteItemModel);
        view.currentActivity().startActivity(intent);
    }

    @Override
    public void onItemLongClick(AdapterView<?> adapterView, View view2, int i, long l) {
        final NoteItemModel noteItemModel = noteItemModels.get(i);
        final String[] items = new String[]{"删除","编辑","编辑字段","取消"};
        new AlertDialog.Builder(view.currentActivity()).setTitle("操作")
        .setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                String item = items[i];
                if ("删除".equalsIgnoreCase(item)){
                    new AlertDialog.Builder(view.currentActivity()).setTitle("提示").setMessage("确定删除"+noteItemModel.getNoteName()+"?")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                    NoteItemFieldModel.deleteAll(NoteItemFieldModel.class,"noteItemId=?",""+noteItemModel.getId());
                                    noteItemModel.delete();
                                    initData();
                                    ToastUtils.show("删除成功");
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    }).show();
                }
                else if ("编辑".equalsIgnoreCase(item)){
                    Intent intent = new Intent(view.currentActivity(), NoteListAddActivity.class);
                    intent.putExtra("data",noteItemModel);
                    view.currentActivity().startActivity(intent);
                }
                else if ("编辑字段".equalsIgnoreCase(item)){
                    Intent intent = new Intent(view.currentActivity(), NoteListEditActivity.class);
                    intent.putExtra("data",noteItemModel);
                    view.currentActivity().startActivity(intent);
                }
            }
        }).show();
    }

    @Override
    public void onDestroy() {
        mCompositeDisposable.clear();
    }

    private List<String> getData() {
        final List<String> titles = new ArrayList<>();
        try {
            noteItemModels = NoteItemModel.listAll(NoteItemModel.class);
            if (null != noteItemModels) {
                    Observable.fromIterable(noteItemModels).map(new Function<NoteItemModel, String>() {
                        @Override
                        public String apply(NoteItemModel noteItemModel) {
                            return noteItemModel.getNoteName();
                        }
                    }).toList().subscribe(new BiConsumer<List<String>, Throwable>() {
                        @Override
                        public void accept(List<String> strings, Throwable throwable) throws Exception {
                            titles.addAll(strings);
                        }
                    });
            }
        }catch (Exception e){
            Log.e(TAG,""+e);
        }
        return titles;
    }
}
